import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { i18n } from '@/i18n'
import { pathToCamel } from '@/utils/tool'

NProgress.configure({ showSpinner: false })

const constantRoutes: RouteRecordRaw[] = [
	{
		name: 'login',
		path: '/login',
		component: () => import('../views/login/index.vue')
	},
	{
		name: 'redirect',
		path: '/redirect',
		component: () => import('../layout/index.vue'),
		children: [
			{
				name: 'redirectpath',
				path: '/redirect/:path(.*)',
				component: () => import('../layout/components/Router/Redirect.vue')
			}
		]
	},
	{
		name: 'gateway',
		path: '/gateway',
		component: () => import('../views/login/gateway.vue')
	},
	{
		name: 'userInfo',
		path: '/userInfo',
		component: () => import('../views/login/userInfo.vue')
	},
	{
		name: 'userInfoTwo',
		path: '/userInfoTwo',
		component: () => import('../views/login/userInfoTwo.vue')
	},
	{
		name: '404',
		path: '/404',
		component: () => import('../views/404.vue')
	}
]

const findNames = array => {
	const names = []
	const loop = arr => {
		arr.map(v => {
			v.name && names.push(v.name)
			if (v.children && v.children.length) {
				loop(v.children)
			}
		})
	}
	loop(array)
	return names
}

export const baseRouterNames = findNames(constantRoutes)

export function RouterInit() {
	const routes = router.getRoutes()
	console.log(baseRouterNames)
	routes.map(v => {
		if (!baseRouterNames.includes(v.name) && v.name) {
			router.removeRoute(v.name)
		}
	})

	console.log(router.getRoutes())
}

const asyncRoutesChildren = [
	{
		path: '/home',
		name: 'Home',
		component: () => import('../views/home.vue'),
		meta: {
			title: i18n.global.t('router.home'),
			affix: true
		}
	},
	{
		path: '/profile/password',
		name: 'ProfilePassword',
		component: () => import('../views/profile/password.vue'),
		meta: {
			title: i18n.global.t('router.profilePassword'),
			cache: true
		}
	},
	{
		path: '/data-assets/resource/db-resource',
		name: 'DataAssetsDbResource',
		component: () => import('../views/data-assets/resource/db-resource.vue'),
		meta: {
			title: '数据库表',
			cache: true
		}
	},
	{
		path: '/data-assets/resource/api-resource',
		name: 'DataAssetsApiResource',
		component: () => import('../views/data-assets/resource/api-resource.vue'),
		meta: {
			title: 'API',
			cache: false
		}
	},
	{
		path: '/data-assets/resource/file-resource',
		name: 'DataAssetsFileResource',
		component: () => import('../views/data-assets/resource/file-resource.vue'),
		meta: {
			title: '文件',
			cache: false
		}
	}
]

// 配置常量菜单
export const constantMenu = [
	{
		id: 1000,
		name: 'Demo',
		url: null,
		openStyle: 0,
		icon: 'icon-windows',
		children: [
			{
				id: 1001,
				name: 'Icon 图标',
				url: 'demo/icons/index',
				openStyle: 0,
				icon: 'icon-unorderedlist'
			},
			{
				id: 1002,
				name: '二维码生成',
				url: 'demo/qrcode/index',
				openStyle: 0,
				icon: 'icon-unorderedlist'
			},
			{
				id: 1003,
				name: '页面打印',
				url: 'demo/printJs/index',
				openStyle: 0,
				icon: 'icon-unorderedlist'
			},
			{
				id: 1004,
				name: '图片裁剪',
				url: 'demo/cropper/index',
				openStyle: 0,
				icon: 'icon-unorderedlist'
			},
			{
				id: 1005,
				name: '富文本编辑器',
				url: 'demo/wangeditor/index',
				openStyle: 0,
				icon: 'icon-unorderedlist'
			}
		]
	}
]

export const errorRoute: RouteRecordRaw = {
	name: 'catch404',
	path: '/:pathMatch(.*)',
	redirect: '/404'
}

export const router = createRouter({
	history: createWebHashHistory(),
	routes: constantRoutes
})

// 白名单列表
const whiteList = ['/login', '/gateway', '/userInfo', '/userInfoTwo']

// 路由加载前
router.beforeEach(async (to, from, next) => {
	if (
		to.path == '/data-development/schedule/index' ||
		to.path == '/data-development/schedule-record/index' ||
		to.path == '/data-governance/metadata-collect/index' ||
		to.path == '/data-governance/metadata-manage/index' ||
		to.path == '/data-governance/metamodel/index' ||
		to.path == '/data-service/api-group/index' ||
		to.path == '/data-service/app/index'
	) {
		to.meta.cache = false
	}
	NProgress.start()
	let token = sessionStorage.getItem('token')
	// token存在的情况
	if (token) {
		if (to.path === '/gateway') {
			await store.userStore.loginOut()
		}
		if (to.path == '/') {
			next('/gateway')
		} else if (to.path == '/gateway' || to.path == '/userInfo' || to.path == '/login' || to.path == '/userInfoTwo') {
			if (to.path == '/login') {
				sessionStorage.removeItem('token')
				sessionStorage.removeItem('loginState')
				sessionStorage.removeItem('userInfoState')
				sessionStorage.removeItem('userInfo')
				sessionStorage.removeItem('platformId')
			}
			next()
		} else {
			// 用户信息不存在，则重新拉取用户等信息
			if (!store.userStore.user.id) {
				// 需要加一个判断
				// console.log(to);
				// console.log(to.path);
				// await store.userStore.newUserChoose()//
				//
				await store.userStore.getUserInfoAction()
				await store.userStore.getAuthorityListAction()
				await store.appStore.getDictListAction()
				// await store.appStore.getProjectListAction()
				// await store.appStore.getSysUserListAction()
				const menuRoutes = await store.routerStore.getMenuRoutes()

				// 根据后端菜单路由，生成KeepAlive路由
				const keepAliveRoutes = getKeepAliveRoutes(menuRoutes, [])
				//console.log("keepAliveRoutes"+JSON.stringify(keepAliveRoutes))

				const asyncRoutes: RouteRecordRaw = {
					name: 'index',
					path: '/',
					component: () => import('../layout/index.vue'),
					children: []
				}

				// 添加菜单路由
				asyncRoutes.children = [...asyncRoutesChildren, ...keepAliveRoutes]
				router.addRoute(asyncRoutes)

				// 错误路由
				router.addRoute(errorRoute)

				// 保存路由数据
				store.routerStore.setRoutes(constantRoutes.concat(asyncRoutes))

				next({ ...to, replace: true })
			} else {
				next()
			}
		}
	} else {
		// if (whiteList.indexOf(to.path) > -1 && to.path != '/login') {
		// 	console.log(1);
		// 	next({ path: '/login' })
		// } else {
		// 	console.log(2);
		// 	next()
		// }
		if (to.path != '/login') {
			next({ path: '/login' })
		} else {
			next()
		}
	}
})

// 路由加载后
router.afterEach(() => {
	NProgress.done()
})

// 获取扁平化路由，将多级路由转换成一级路由
export const getKeepAliveRoutes = (rs: RouteRecordRaw[], breadcrumb: string[]): RouteRecordRaw[] => {
	const routerList: RouteRecordRaw[] = []

	rs.forEach((item: any) => {
		if (item.meta.title) {
			breadcrumb.push(item.meta.title)
		}

		if (item.children && item.children.length > 0) {
			routerList.push(...getKeepAliveRoutes(item.children, breadcrumb))
		} else {
			item.meta.breadcrumb.push(...breadcrumb)
			routerList.push(item)
		}

		breadcrumb.pop()
	})
	return routerList
}

// 加载vue组件
const layoutModules = import.meta.glob('/src/views/**/*.vue')

// 根据路径，动态获取vue组件
const getDynamicComponent = (path: string): any => {
	const component = layoutModules[`/src/views/${path}.vue`]
	if (!component) {
		console.log('组件不存在，路径为：', path)
	}
	return component
}

// 根据菜单列表，生成路由数据
export const generateRoutes = (menuList: any): RouteRecordRaw[] => {
	const routerList: RouteRecordRaw[] = []

	menuList.forEach((menu: any) => {
		let component
		let path
		if (menu.children && menu.children.length > 0) {
			component = () => import('@/layout/index.vue')
			path = '/p/' + menu.id
		} else {
			component = getDynamicComponent(menu.url)
			path = '/' + menu.url
		}
		const route: RouteRecordRaw = {
			path: path,
			name: pathToCamel(path),
			component: component,
			children: [],
			meta: {
				title: menu.name,
				icon: menu.icon,
				id: '' + menu.id,
				cache: true,
				_blank: menu.openStyle === 1,
				url: menu.url,
				breadcrumb: []
			}
		}

		// 有子菜单的情况
		if (menu.children && menu.children.length > 0) {
			route.children?.push(...generateRoutes(menu.children))
		}

		routerList.push(route)
	})

	return routerList
}
